package com.spooky.sync.persistence.db;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class UpdateSql extends SQLiteOpenHelper {
	private static final String TAG = "UpdateSql";
	protected SyntaxCreator mSyntaxCreator;
	private static UpdateSql mUpdateSql = null;

	private UpdateSql(Context context) {
		super(context, TableCreateSyntax.DATABASE, null, TableCreateSyntax.DATABASE_VERSION);
		mSyntaxCreator = new TableCreateSyntax();
	}

	public static UpdateSql getInstance(Context context) {
		if (mUpdateSql == null) {
			mUpdateSql = new UpdateSql(context);
		}
		return mUpdateSql;
	}

	public static void onDestroy() {
		if (mUpdateSql != null) {
			mUpdateSql.close();
		}
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		Log.d(TAG, "Creating database.");
		create(db);
		Log.d(TAG, "Created database.");
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		Log.d(TAG, "Upgrading database.");
		for (int i = oldVersion + 1; i <= newVersion; ++i) {
			upgrade(db, i);
		}
	}

	private void upgrade(SQLiteDatabase db, int version) {
		for (String command : mSyntaxCreator.getGetUpdateSyntax(version)) {
			db.execSQL(command);
		}
	}

	private void drop(SQLiteDatabase db) {
		try {
			for (String table : mSyntaxCreator.getTables()) {
				try {
					db.execSQL(String.format("DROP TABLE %s IF EXISTS;", table));
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void create(SQLiteDatabase db) {
		try {
			for (String create : mSyntaxCreator.create()) {
				try {
					db.execSQL(create);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
